<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的车票 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand" href="/">
            <i class="fas fa-train me-2"></i>列车车次管理系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/">首页</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/user/booking">车票预订</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/user/tickets">我的车票</a>
                </li>
            </ul>
            <ul class="navbar-nav" id="authNav">
                <!-- 动态填充登录状态 -->
            </ul>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="bi bi-ticket-perforated me-2"></i>我的车票</h5>
                    <div>
                        <select id="statusFilter" class="form-select form-select-sm" style="width: auto;">
                            <option value="">全部状态</option>
                            <option value="CONFIRMED">已确认</option>
                            <option value="PENDING">待确认</option>
                            <option value="CANCELLED">已取消</option>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div id="loadingArea" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">正在加载车票信息...</p>
                    </div>

                    <div id="ticketsArea" class="d-none">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>票号</th>
                                        <th>车次</th>
                                        <th>出发站</th>
                                        <th>到达站</th>
                                        <th>出发时间</th>
                                        <th>座位类型</th>
                                        <th>乘客姓名</th>
                                        <th>票价</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="ticketsTable">
                                    <!-- 动态加载车票数据 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="noTicketsArea" class="text-center py-5 d-none">
                        <i class="bi bi-ticket-perforated" style="font-size: 4rem; color: #dee2e6;"></i>
                        <h5 class="text-muted mt-3">暂无车票记录</h5>
                        <p class="text-muted">您还没有预订过车票</p>
                        <a href="/user/booking.html" class="btn btn-primary">
                            <i class="bi bi-plus-circle me-2"></i>立即预订
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 车票详情模态框 -->
<div class="modal fade" id="ticketDetailModal" tabindex="-1" aria-labelledby="ticketDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ticketDetailModalLabel">
                    <i class="bi bi-ticket-detailed me-2"></i>车票详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="ticketDetailContent">
                <!-- 动态加载车票详情 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 退票确认模态框 -->
<div class="modal fade" id="cancelTicketModal" tabindex="-1" aria-labelledby="cancelTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancelTicketModalLabel">
                    <i class="bi bi-exclamation-triangle me-2"></i>确认退票
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要退掉这张车票吗？</p>
                <div class="alert alert-warning">
                    <i class="bi bi-info-circle me-2"></i>
                    退票后将按照铁路部门规定收取手续费，请谨慎操作。
                </div>
                <div id="cancelTicketInfo">
                    <!-- 动态显示要退票的信息 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmCancelBtn">确认退票</button>
            </div>
        </div>
    </div>
</div>

<footer class="bg-light text-center text-lg-start mt-5">
    <div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.05);">
        © 2025 列车车次管理系统 -
        <a class="text-dark" href="/">upup.com</a>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/js/auth.js"></script>
<script>
    let allTickets = [];
    let currentTicketId = null;

    $(document).ready(function() {
        // 检查用户登录状态
        updateAuthNav();
        checkUserLogin();

        // 加载车票数据
        loadUserTickets();

        // 绑定状态筛选事件
        $('#statusFilter').on('change', function() {
            filterTickets();
        });

        // 绑定退票确认事件
        $('#confirmCancelBtn').on('click', function() {
            if (currentTicketId) {
                cancelTicket(currentTicketId);
            }
        });
    });

    // 检查用户登录状态
    function checkUserLogin() {
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            error: function() {
                alert('请先登录');
                window.location.href = '/custom-login?redirect=' + encodeURIComponent(window.location.href);
            }
        });
    }

    // 加载用户车票
    function loadUserTickets() {
        $('#loadingArea').removeClass('d-none');
        $('#ticketsArea').addClass('d-none');
        $('#noTicketsArea').addClass('d-none');

        $.ajax({
            url: '/api/tickets/user',
            type: 'GET',
            success: function(tickets) {
                allTickets = tickets;
                $('#loadingArea').addClass('d-none');
                
                if (tickets.length === 0) {
                    $('#noTicketsArea').removeClass('d-none');
                } else {
                    $('#ticketsArea').removeClass('d-none');
                    renderTickets(tickets);
                }
            },
            error: function(xhr) {
                $('#loadingArea').addClass('d-none');
                $('#ticketsArea').removeClass('d-none');
                $('#ticketsTable').html(`
                    <tr>
                        <td colspan="10" class="text-center text-danger">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            加载失败：${xhr.responseText || '网络错误'}
                        </td>
                    </tr>
                `);
            }
        });
    }

    // 渲染车票列表
    function renderTickets(tickets) {
        if (tickets.length === 0) {
            $('#ticketsTable').html('<tr><td colspan="10" class="text-center text-muted">没有找到符合条件的车票</td></tr>');
            return;
        }

        let html = '';
        tickets.forEach(ticket => {
            const statusBadge = getStatusBadge(ticket.status);
            const canCancel = ticket.status === 'CONFIRMED' && new Date(ticket.departureDate + ' ' + ticket.departureTime) > new Date();
            
            html += `
                <tr>
                    <td>
                        <strong class="text-primary">${ticket.ticketNumber}</strong>
                    </td>
                    <td>${ticket.trainNumber}</td>
                    <td>${ticket.startStationName}</td>
                    <td>${ticket.endStationName}</td>
                    <td>
                        <div>${ticket.departureDate}</div>
                        <small class="text-muted">${ticket.departureTime}</small>
                    </td>
                    <td>
                        <span class="badge bg-info">${ticket.seatClass}</span>
                    </td>
                    <td>${ticket.passengerName}</td>
                    <td class="text-success">¥${ticket.price ? ticket.price.toFixed(2) : '0.00'}</td>
                    <td>${statusBadge}</td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary view-detail-btn" 
                                    data-id="${ticket.id}" 
                                    data-bs-toggle="tooltip" 
                                    title="查看详情">
                                <i class="bi bi-eye"></i>
                            </button>
                            ${canCancel ? `
                                <button class="btn btn-outline-danger cancel-btn" 
                                        data-id="${ticket.id}" 
                                        data-info="${ticket.trainNumber} ${ticket.startStationName}→${ticket.endStationName}"
                                        data-bs-toggle="tooltip" 
                                        title="退票">
                                    <i class="bi bi-x-circle"></i>
                                </button>
                            ` : ''}
                        </div>
                    </td>
                </tr>
            `;
        });

        $('#ticketsTable').html(html);

        // 重新绑定事件
        bindTicketEvents();
        
        // 初始化工具提示
        if (typeof bootstrap !== 'undefined') {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        }
    }

    // 绑定车票相关事件
    function bindTicketEvents() {
        // 查看详情事件
        $('.view-detail-btn').on('click', function() {
            const ticketId = $(this).data('id');
            showTicketDetail(ticketId);
        });

        // 退票事件
        $('.cancel-btn').on('click', function() {
            currentTicketId = $(this).data('id');
            const ticketInfo = $(this).data('info');
            $('#cancelTicketInfo').html(`
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">车票信息</h6>
                        <p class="card-text">${ticketInfo}</p>
                    </div>
                </div>
            `);
            $('#cancelTicketModal').modal('show');
        });
    }

    // 获取状态徽章
    function getStatusBadge(status) {
        switch(status) {
            case 'CONFIRMED':
                return '<span class="badge bg-success">已确认</span>';
            case 'PENDING':
                return '<span class="badge bg-warning">待确认</span>';
            case 'CANCELLED':
                return '<span class="badge bg-danger">已取消</span>';
            default:
                return '<span class="badge bg-secondary">未知</span>';
        }
    }

    // 筛选车票
    function filterTickets() {
        const status = $('#statusFilter').val();
        if (!status) {
            renderTickets(allTickets);
        } else {
            const filteredTickets = allTickets.filter(ticket => ticket.status === status);
            renderTickets(filteredTickets);
        }
    }

    // 显示车票详情
    function showTicketDetail(ticketId) {
        const ticket = allTickets.find(t => t.id === ticketId);
        if (!ticket) {
            alert('车票信息不存在');
            return;
        }

        const detailHtml = `
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0">车票详细信息</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>票号：</strong>${ticket.ticketNumber}</p>
                            <p><strong>车次：</strong>${ticket.trainNumber}</p>
                            <p><strong>乘客姓名：</strong>${ticket.passengerName}</p>
                            <p><strong>身份证号：</strong>${ticket.passengerIdCard}</p>
                            <p><strong>联系电话：</strong>${ticket.contactPhone}</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>出发站：</strong>${ticket.startStationName}</p>
                            <p><strong>到达站：</strong>${ticket.endStationName}</p>
                            <p><strong>出发日期：</strong>${ticket.departureDate}</p>
                            <p><strong>出发时间：</strong>${ticket.departureTime}</p>
                            <p><strong>到达时间：</strong>${ticket.arrivalTime}</p>
                        </div>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>座位类型：</strong><span class="badge bg-info">${ticket.seatClass}</span></p>
                            <p><strong>票价：</strong><span class="text-success">¥${ticket.price ? ticket.price.toFixed(2) : '0.00'}</span></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>预订时间：</strong>${new Date(ticket.createTime).toLocaleString()}</p>
                            <p><strong>状态：</strong>${getStatusBadge(ticket.status)}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        $('#ticketDetailContent').html(detailHtml);
        $('#ticketDetailModal').modal('show');
    }

    // 退票
    function cancelTicket(ticketId) {
        $.ajax({
            url: `/api/tickets/${ticketId}/cancel`,
            type: 'PUT',
            success: function() {
                $('#cancelTicketModal').modal('hide');
                alert('退票成功');
                loadUserTickets(); // 重新加载车票列表
            },
            error: function(xhr) {
                alert('退票失败：' + (xhr.responseText || '请稍后重试'));
            }
        });
    }
</script>
</body>
</html>
